package com.huanghuai.retail.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huanghuai.retail.common.R;
import com.huanghuai.retail.entity.PType;
import com.huanghuai.retail.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/type")
public class TypeController {

    @Autowired
    private TypeService typeService;


    /**
     * 根据id查询type信息
     * @param id
     * @return
     */
    @GetMapping("getById/{id}")
    public R<PType> getById(@PathVariable Long id){

        if(id == null || id < 0 || typeService.getById(id) == null)
            return R.error("查询失败");

        return R.success(typeService.getById(id));
    }

    /**
     * 分页查询类别列表
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R<Page> findAll(@RequestParam(defaultValue = "1")int page,
                           @RequestParam(defaultValue = "10")int pageSize){

        Page<PType> pageInfo = new Page<>(page, pageSize);

        typeService.page(pageInfo);

        if (0 == pageInfo.getRecords().size())
            return R.error("未查询到类别信息");

        return R.success(pageInfo);
    }

    /**
     * 查询所有品牌，用于新增品牌或者商品时展示列表
     * @return
     */
    @GetMapping("findAll")
    public R<List<PType>> findAll(){

        List<PType> list = typeService.list();
        if (list == null)
            return R.error("查询类型列表失败");

        return R.success(list);
    }

    /**
     * 新增类别
     * @param type
     * @return
     */
    @PostMapping("add")
    public R<String> add(@RequestBody PType type){

        if (type.getNameOne() == null
                || type.getNameTwo() == null
                || type.getNameOne().length() == 0
                || type.getNameTwo().length() == 0)
            return R.error("类型信息不全，新增失败");

        typeService.save(type);
        return R.success("新增商品类型成功");
    }

    /**
     * 跟新类别信息
     * @param type
     * @return
     */
    @PutMapping("update")
    public R<String> update(@RequestBody PType type){

        if (type.getId() == null || typeService.getById(type.getId()) == null)
            return R.error("找不到对应类型，修改失败");

        if (type.getNameOne() == null
                || type.getNameTwo() == null
                || type.getNameOne().length() == 0
                || type.getNameTwo().length() == 0)
            return R.error("类型信息不全，新增失败");

        typeService.updateById(type);
        return R.success("修改成功");
    }

    @GetMapping("/findAllName")
      public R<List<PType>> findAllName() {
        R<List<PType>> typeAllName = typeService.findAllName();
        return R.success(typeAllName.getData());

    }
}
